<?php

namespace app\service\api;

use app\common\BaseResult;
use app\common\enum\ScopeEnum;
use app\facade\model\AdminUser;
use think\Db;

class YuwenService
{
    public function lists($request)
    {
        $user_scope = $request->user->scope;
        $pagesize   = $request->param('pagesize', 10);
        $page       = $request->param('page', 1);
        $scope      = $request->param('scope', $user_scope);
        $keywords   = trim($request->param('keywords', ''));

        $where = [];
        if ($scope === ScopeEnum::DEVELOPER) {
            $where[] = ['scope', '<>', ScopeEnum::SUPPLIER];
            $where[] = ['scope', '<>', ''];
        }else{
            // $where[] = ['scope', '=', $scope];
            $where[] = ['scope', '=', 'super'];
        }
        if ($keywords) {
            $where[] = ['username', 'like', '%'.$keywords.'%'];
        }

        $order = ['id' => 'desc'];
        $users = AdminUser::users($where,'*', $order, $pagesize, $page);
        foreach($users as &$user){
            $user->getAllRoles();
        }
        unset($user);
        $users->hidden(['login_time','login_ip','lock','create_time','update_time','expired_time','activationtime','num','token','description','scope','scope_id','isNotice']);
        return $users;
    }

    public function createUser($data)
    {
        if (AdminUser::where([
            'scope' => trim($data['scope']),
            'scope_id' => trim($data['scope_id'])
        ])->find()) {
            return BaseResult::error('用户信息已设置');
        }
        Db::startTrans();
        if(!$admin = AdminUser::create([
            'username'    => $data['username'],
            'password'    => isset($data['password']) ? AdminUser::encrypt($data['password']) :  AdminUser::encrypt("123456"),
            'scope'       => trim($data['scope']),
            'scope_id'    => intval($data['scope_id']),
            'is_forbid'   => intval($data['is_forbid']),
            'avatar'      => $data['avatar'] ?? '',
            'description' => $data['description'] ?? '',
            'email'       => $data['email'] ?? '',
            'nickname'    => $data['nickname'] ?? '',
        ]) ) {
            Db::rollback();
            return BaseResult::error('请联系管理员');
        }

        try {
            # 检查权限是否存在
            if(isset($data['role_ids'])) {
                $admin->syncRole($data['permission_ids']); # 这里面已经有事务操作了
            }
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            return BaseResult::error($e->getMessage());
        }

        return BaseResult::succ();
    }


    public function updateUser($id, $data)
    {
        $set_data = [
            'username'    => $data['username'],
            'is_forbid'   => intval($data['is_forbid']),
            'avatar'      => $data['avatar'] ?? '',
            'description' => $data['description'] ?? '',
            'email'       => $data['email'] ?? '',
            'nickname'    => $data['nickname'] ?? '',
            'isNotice'    => $data['isNotice'] ?? 1,
        ];
        if (array_key_exists('password',$data) && !empty($data['password'])) {
            $set_data['password'] = AdminUser::encrypt($data['password']);
        }

        if(!$admin = AdminUser::find($id)) {
            return BaseResult::error('你不能操作管理员');
        }
        if(AdminUser::checkIsAdmin($admin)) {
            return BaseResult::error('无法在当前页面更新这个用户信息');
        }

        Db::startTrans();
        AdminUser::update($set_data, compact('id'));
        try {
            # 检查权限是否存在
            if(isset($data['role_ids'])) {
                $admin->syncRole($data['role_ids']); # 这里面已经有事务操作了
            }
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            return BaseResult::error($e->getMessage());
        }

        return BaseResult::succ(AdminUser::find($id));
    }

    public function delUser(int $id)
    {
        $admin = AdminUser::getRowInfoById($id);
        if($admin) {
            if(AdminUser::checkIsAdmin($admin)) {
                return BaseResult::error('你不能操作管理员');
            }
            $admin->delete();
            return BaseResult::succ(null, '删除成功');
        }
        return BaseResult::error('信息不存在');
    }

    public function getUser(int $id)
    {
        // $admin = AdminUser::with(['roles'])->find($id);
        $admin = AdminUser::find($id);
        if($admin) {
            $admin->roles = $admin->getAllRoles();
            return BaseResult::succ(null, $admin->toArray());
        }

        return BaseResult::error('管理员未找到');
    }

    public function getAdminInfo(){
        
    }
   
}
